package org.acghub.mtdb.core;

import org.acghub.mtdb.common.Pair;
import org.acghub.mtdb.common.exception.LifecycleException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhouhe
 */
public abstract class AbstractTableStorage<K, V> implements TableStorage<K, V> {
    protected final Map<K, TRecord<K, V>> changed = new ConcurrentHashMap<>();

    protected final ReadWriteLock snapshotLock = new ReentrantReadWriteLock();

    protected StorageEngine storageEngine;

    protected Table<K, V> table;

    protected Map<K, TRecord<K, V>> marshal = new ConcurrentHashMap<>();

    protected Map<K, TRecord<K, V>> snapshot = new ConcurrentHashMap<>();

    @Override
    public final void init(Pair<Table<K, V>, StorageEngine> pair) throws LifecycleException {
        this.table = pair.getLeft();
        this.storageEngine = pair.getRight();
    }

    @Override
    public final void close() throws LifecycleException {
        storageEngine.close();
        storageEngine = null;
        table = null;
    }

    public org.acghub.mtdb.common.Table meta() {
        return table().meta();
    }

    @Override
    public StorageEngine engine() {
        return storageEngine;
    }

    @Override
    public org.acghub.mtdb.core.Table<K, V> table() {
        return table;
    }
}
